<template>
  <div>
    <a-space direction="vertical" style="width:100%" size="middle">
      <a-card title="部署列表" :loading="loading">
        <template #extra>
          <a-upload :before-upload="beforeUpload" :show-upload-list="false">
            <a-button type="primary">上传并部署 BPMN</a-button>
          </a-upload>
        </template>
        <a-table :columns="columns" :data-source="deployments" row-key="id" size="small" :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'actions'">
              <a-space>
                <a-popconfirm title="直接删除部署(可能失败)?" @confirm="() => remove(record.id)">
                  <a-button danger size="small">硬删除</a-button>
                </a-popconfirm>
                <a-button size="small" @click="() => safeRemove(record.id)">安全删除</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-space>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { listDeployments, deleteDeployment, deployBpmn, safeDeleteDeployment } from '../services/flowable';

const loading = ref(false);
const deployments = ref<any[]>([]);

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '时间', dataIndex: 'deploymentTime', key: 'deploymentTime' },
  { title: 'Actions', key: 'actions' }
];

async function load() {
  loading.value = true;
  try {
    deployments.value = await listDeployments();
  } catch (e:any) {
    message.error(e.message || '加载失败');
  } finally {
    loading.value = false;
  }
}

async function remove(id:string) {
  try {
    await deleteDeployment(id);
    message.success('删除成功');
    load();
  } catch (e:any) {
    message.error(e.message || '删除失败');
  }
}

async function safeRemove(id:string) {
  loading.value = true;
  try {
    const { definitions, instancesDeleted } = await safeDeleteDeployment(id);
    message.success(`安全删除成功，清理实例 ${instancesDeleted} 个，定义 ${definitions} 个`);
    load();
  } catch (e:any) {
    message.error(e.message || '安全删除失败');
  } finally {
    loading.value = false;
  }
}

function beforeUpload(file:File) {
  const reader = new FileReader();
  reader.onload = async () => {
    try {
      const result = await deployBpmn(file);
      const saved = result?.tasks_saved ?? 0;
      message.success(`部署成功，已同步节点 ${saved} 个`);
      load();
    } catch (e:any) {
      message.error(e?.message || '部署失败');
    }
  };
  reader.readAsArrayBuffer(file);
  return false; // prevent auto upload
}

onMounted(load);
</script>
